import cv2 as cv
import face_recognition as fr
import numpy as np
import config.config as cfg
import time

#采用缓存机制的人脸detect

facelocation_cache =[]
frame_cache =[]
def detect_face_cache(frame):
    #帧计数器
    cfg.frame_counter += 1

    global facelocation_cache,frame_cache



    if cfg.frame_counter % cfg.size == 0:
        facelocation = fr.face_locations(frame)
        for top, right, down, left in facelocation:
            cv.rectangle(frame, (left, top), (right, down), (0, 255, 0), 2)
        frame_cache = frame
        facelocation_cache = facelocation

    return facelocation_cache, frame_cache


def detect_face(frame):
    start_time = time.time()
    facelocation = fr.face_locations(frame)
    for top, right, down, left in facelocation:
        cv.rectangle(frame, (left, top), (right, down), (0, 255, 0), 2)
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"绘制人脸用时{elapsed_time}")
    return frame,facelocation

#提取特征值
def getencodings(image, face_locations):
    start = time.time()
    cfg.frame_counter = cfg.frame_counter + 1
    encodings = fr.face_encodings(image, face_locations)
    end = time.time()
    cfg.total_time += (end - start)
    if cfg.frame_counter % 10 == 0:  # 每10帧打印一次平均时间
        print(f"提取特征值平均耗时: {cfg.total_time / 10:.6f}秒")
        cfg.total_time = 0  # 重置计时器
    return encodings

#创建掩模
def create_mask(image, facelocations):
    # 创建一个全白的掩模图像，和原图像大小一致
    mask = np.ones_like(image, dtype=np.uint8) * 255  # 全白的掩模图像

    # 在掩模图像上标记出人脸区域（将这些区域标记为0）
    for (top, right, bottom, left) in facelocations:
        cv.rectangle(mask, (left, top), (right, bottom), (0, 0, 0), -1)  # 用黑色填充人脸区域

    return mask


def cv_detect(image):
    start_time = time.time()

    # 加载预训练的 Haar Cascade 模型
    face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    # 在检测到的人脸周围绘制矩形
    for (x, y, w, h) in faces:
        cv.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"cv模型定位人脸用时{elapsed_time}")

    return image,faces

